﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.Entity;
using CRM.BLL;
using DP.Web.UI;
using DP.Common;

namespace CRM.Web.ServiceQualityRepot
{
    public partial class Modify : Common.PageBase
    {

        T_BUSINESSDIVISION_BLL bdBll = new T_BUSINESSDIVISION_BLL();
        T_SERVICEQUALITYREPOT_BLL bll = new T_SERVICEQUALITYREPOT_BLL();
        T_REPAIRCASE_BLL repairCaseBll = new T_REPAIRCASE_BLL();
        T_COMPLAINTCASE_BLL complaintCaseBll = new T_COMPLAINTCASE_BLL();



        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageHelper.SetPrePageUrl(this.Page);
            if (PageHelper.GetQueryString(this.Page, "PageTarget") != "Opener")
            {
                PageHelper.SetGoBackUrl(this.Page, btnCancel, StaticConstant.NotBackUrl);
                btnCancel.Attributes["onclick"] = UserLoginInfo.FilterBackUrl(btnCancel.Attributes["onclick"]);
            }
            else
            {
                PageHelper.SetClose(this.Page, btnCancel);
                btnCancel.Value = "关 闭";
            }
            PageHelper.SetPopCalender(this.Page, txtMAINTENANCEDATE);
            PageHelper.SetPopCalender(this.Page, txtMANUFACTUREDATE);
            PageHelper.SetPopCalender(this.Page, txtSALEDATE);
            PageHelper.SetPopCalender(this.Page, txtRETURNDATE);
            PageHelper.SetPopCalender(this.Page, txtCREATETIME);
            PageHelper.SetPopCalender(this.Page, txtLASTMODIFYTIME);

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                ddlSTATUSBinding();


                pageDataInit();
            }
        }

        #region 页面初始化数据绑定


        /// <summary>
        /// DDLs the STATE binding.
        /// </summary>
        private void ddlSTATUSBinding()
        {
            ddlSTATUS.Items.Clear();
            EnumHelper.FillListControl(ddlSTATUS, typeof(ServiceQualityStatus));
            ddlSTATUS.Items.Insert(0, new ListItem("", ""));
        }



        #endregion

        private void pageDataInit()
        {
            string _servicerepotid = String.IsNullOrEmpty(Request.QueryString["SERVICEREPOTID"]) ? "" : Request.QueryString["SERVICEREPOTID"].Trim();

            if (!String.IsNullOrEmpty(_servicerepotid))
            {
                T_SERVICEQUALITYREPOT_Entity entity = bll.GetEntity("SERVICEREPOTID", _servicerepotid);

                PageHelper.SetControlValue<T_SERVICEQUALITYREPOT_Entity>(this.Page, entity);
                txtMAINTENANCEDATE.Text = entity.MAINTENANCEDATE.HasValue ? entity.MAINTENANCEDATE.Value.ToString("yyyy-MM-dd") : "";
                txtMANUFACTUREDATE.Text = entity.MANUFACTUREDATE.HasValue ? entity.MANUFACTUREDATE.Value.ToString("yyyy-MM-dd") : "";
                txtSALEDATE.Text = entity.SALEDATE.HasValue ? entity.SALEDATE.Value.ToString("yyyy-MM-dd") : "";
                txtPROCESSINGCOMPLETEDTIME.Text = entity.PROCESSINGCOMPLETEDTIME.HasValue ? entity.PROCESSINGCOMPLETEDTIME.Value.ToString("yyyy-MM-dd") : "";

                hlVEHICLEPLATEIMAGE.Text = entity.VEHICLEPLATEIMAGE;
                hlVEHICLEPLATEIMAGE.NavigateUrl = GetVirtualPath(entity.VEHICLEPLATEIMAGE);
                hlPICTURECONDITIONIMAGE.Text = entity.PICTURECONDITIONIMAGE;
                hlPICTURECONDITIONIMAGE.NavigateUrl = GetVirtualPath(entity.PICTURECONDITIONIMAGE);
                hlVISIONPICTURE.Text = entity.VISIONPICTURE;
                hlVISIONPICTURE.NavigateUrl = GetVirtualPath(entity.VISIONPICTURE);
                hlCLOSERANGEPICTURES.Text = entity.CLOSERANGEPICTURES;
                hlCLOSERANGEPICTURES.NavigateUrl = GetVirtualPath(entity.CLOSERANGEPICTURES);
                hlMACROPICTURE.Text = entity.MACROPICTURE;
                hlMACROPICTURE.NavigateUrl = GetVirtualPath(entity.MACROPICTURE);

                if (!String.IsNullOrEmpty(entity.STATUS))
                {
                    switch ((ServiceQualityStatus)Enum.Parse(typeof(ServiceQualityStatus), entity.STATUS.Trim()))
                    {
                        case ServiceQualityStatus.新建:
                            {
                                btnReSubmit.Visible = true;
                            }
                            break;
                        case ServiceQualityStatus.提交:
                            {
                                btnPass.Visible = true;
                                btnReject.Visible = true;
                            }
                            break;
                        case ServiceQualityStatus.审核通过:
                            {

                            }
                            break;
                    }                        
                }

                lblTitle.Text = "质量信息报告处理";
            }
            else
            {
                string caseType = PageHelper.GetQueryString(this.Page, "CASETYPE");
                string caseId = PageHelper.GetQueryString(this.Page, "CASEID");
                if (!String.IsNullOrEmpty(caseType) && !String.IsNullOrEmpty(caseId))
                {
                    switch (caseType)
                    {
                        case "2":
                            {
                                T_REPAIRCASE_Entity repairCaseEntity = repairCaseBll.GetEntity("CASEID", caseId);
                                txtCASETYPE.Text = caseType;
                                txtCASEID.Text = repairCaseEntity.CASEID.ToString();
                                txtVINCODE.Text = repairCaseEntity.VINCODE;
                                txtPRODUCTCODE.Text = repairCaseEntity.PRODUCTCODE;
                                txtSERIES.Text = repairCaseEntity.SERIES;
                                txtMODELS.Text = repairCaseEntity.MODELS;
                                txtENGINEMODEL.Text = repairCaseEntity.ENGINEMODEL;
                                txtENGINENUMBER.Text = repairCaseEntity.ENGINENUMBER;
                                txtCUSTOMERNAME.Text = repairCaseEntity.OWNERSPEOPLE;
                                txtCUSTOMERTEL.Text = repairCaseEntity.OWNERSMOBILEPHONE;
                                txtCONTACT.Text = repairCaseEntity.CUSTOMERNAME;
                                txtCONTACTTEL.Text = repairCaseEntity.FIRSTCONTACTTEL;
                                if (!String.IsNullOrEmpty(repairCaseEntity.PROCESSINGUSERNAME))
                                {
                                    string[] tels = repairCaseEntity.PROCESSINGUSERNAME.Trim().Split(new char[] { ';', ',', '；', '，' });
                                    if (tels.Length > 0)
                                    {
                                        if (tels[0].IndexOf('*') >= 0)
                                        {
                                            txtMAINTENANCESTAFFTEL.Text = tels[0].Substring(0, tels[0].IndexOf('*'));
                                            txtMAINTENANCESTAFF.Text = tels[0].Substring(tels[0].IndexOf('*') + 1);
                                        }
                                    }
                                }
                                txtSALEDATE.Text = repairCaseEntity.PURCHASEDATE.HasValue ? repairCaseEntity.PURCHASEDATE.Value.ToString("yyyy-MM-dd") : "";
                                txtFAULTNAME.Text = repairCaseEntity.FAILUREPARTS;
                                txtFAULTDRAWINGNO.Text = "";
                                txtFAULTLOCATIONCODE.Text = repairCaseEntity.FAILUREPARTSCODE;
                                txtFAULTCODE.Text = repairCaseEntity.FAULTCODE;
                                txtSYMPTOM.Text = repairCaseEntity.SYMPTOM;
                                txtPROCESSINGCOMPLETEDTIME.Text = repairCaseEntity.PROCESSINGCOMPLETEDTIME.HasValue ? repairCaseEntity.PROCESSINGCOMPLETEDTIME.Value.ToString("yyyy-MM-dd") : "";
                                txtFAILUREREASON.Text = repairCaseEntity.FAILUREANALYSIS;
                                txtFAULTWORKPLANE.Text = repairCaseEntity.FAILUREOCCURS;


                            }
                            break;
                        case "3":
                            {
                                T_COMPLAINTCASE_Entity complaintCaseEntity = complaintCaseBll.GetEntity("CASEID", caseId);
                                txtCASETYPE.Text = caseType;
                                txtCASEID.Text = complaintCaseEntity.CASEID.ToString();
                                txtVINCODE.Text = complaintCaseEntity.VINCODE;
                                txtPRODUCTCODE.Text = complaintCaseEntity.PRODUCTCODE;
                                txtSERIES.Text = complaintCaseEntity.SERIES;
                                txtMODELS.Text = complaintCaseEntity.MODELS;
                                txtENGINEMODEL.Text = complaintCaseEntity.ENGINEMODEL;
                                txtENGINENUMBER.Text = complaintCaseEntity.ENGINENUMBER;
                                txtCUSTOMERNAME.Text = complaintCaseEntity.OWNERSPEOPLE;
                                txtCUSTOMERTEL.Text = complaintCaseEntity.OWNERSMOBILEPHONE;
                                txtCONTACT.Text = complaintCaseEntity.CUSTOMERNAME;
                                txtCONTACTTEL.Text = complaintCaseEntity.FIRSTCONTACTTEL;
                                if (!String.IsNullOrEmpty(complaintCaseEntity.PROCESSINGUSERNAME))
                                {
                                    string[] tels = complaintCaseEntity.PROCESSINGUSERNAME.Trim().Split(new char[] { ';', ',', '；', '，' });
                                    if (tels.Length > 0)
                                    {
                                        if (tels[0].IndexOf('*') >= 0)
                                        {
                                            txtMAINTENANCESTAFFTEL.Text = tels[0].Substring(0, tels[0].IndexOf('*'));
                                            txtMAINTENANCESTAFF.Text = tels[0].Substring(tels[0].IndexOf('*') + 1);
                                        }
                                    }
                                }
                                txtSALEDATE.Text = complaintCaseEntity.PURCHASEDATE.HasValue ? complaintCaseEntity.PURCHASEDATE.Value.ToString("yyyy-MM-dd") : "";
                                //txtFAULTNAME.Text = complaintCaseEntity.FAILUREPARTS;
                                txtFAULTDRAWINGNO.Text = "";
                                //txtFAULTLOCATIONCODE.Text = complaintCaseEntity.FAILUREPARTSCODE;
                                //txtFAULTCODE.Text = complaintCaseEntity.FAULTCODE;
                                //txtSYMPTOM.Text = complaintCaseEntity.SYMPTOM;
                                txtPROCESSINGCOMPLETEDTIME.Text = complaintCaseEntity.PROCESSINGCOMPLETEDTIME.HasValue ? complaintCaseEntity.PROCESSINGCOMPLETEDTIME.Value.ToString("yyyy-MM-dd") : "";
                                //txtFAILUREREASON.Text = complaintCaseEntity.FAILUREANALYSIS;
                                //txtFAULTWORKPLANE.Text = complaintCaseEntity.FAILUREOCCURS;
                            }
                            break;
                    }

                }

                btnOK.Visible = true;

                lblTitle.Text = "质量信息报告提交";
                txtBUSINESSDIVISIONNAME.Text = _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME;
                txtDEPARTMENTNAME.Text = _userLoginInfo.UserEntity.DEPARTMENTNAME;
                txtCREATETIME.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtLASTMODIFYTIME.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtCREATEPEOPLE.Text = _userLoginInfo.UserEntity.USERNAME;
                txtLASTMODIFYPEOPLE.Text = _userLoginInfo.UserEntity.USERNAME;

            }
            txtCREATEPEOPLE.Enabled = false;
            txtCREATETIME.Enabled = false;
            txtLASTMODIFYPEOPLE.Enabled = false;
            txtLASTMODIFYTIME.Enabled = false;
            txtBUSINESSDIVISIONNAME.Enabled = false;
            txtDEPARTMENTNAME.Enabled = false;

            txtSERVICEREPOTID.Enabled = false;
            ddlSTATUS.Enabled = false;

        }

        /// <summary>
        /// Handles the Click event of the btnUpload control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string virtualPath = string.Empty;
            string actualPath = string.Empty;
            string fileName = string.Empty;
            Button btn = sender as Button;
            if (btn == null)
            {
                return;
            }

            switch (btn.ID.ToString())
            {
                case "btnUploadVEHICLEPLATEIMAGE":
                    {
                        UploadFile(this.Page, fuVEHICLEPLATEIMAGE, ref virtualPath, ref actualPath, ref fileName);
                        hlVEHICLEPLATEIMAGE.Text = fileName;
                        hlVEHICLEPLATEIMAGE.NavigateUrl = virtualPath;

                    }
                    break;
                case "btnUploadPICTURECONDITIONIMAGE":
                    {
                        UploadFile(this.Page, fuPICTURECONDITIONIMAGE, ref virtualPath, ref actualPath, ref fileName);
                        hlPICTURECONDITIONIMAGE.Text = fileName;
                        hlPICTURECONDITIONIMAGE.NavigateUrl = virtualPath;

                    }
                    break;
                case "btnUploadVISIONPICTURE":
                    {
                        UploadFile(this.Page, fuVISIONPICTURE, ref virtualPath, ref actualPath, ref fileName);
                        hlVISIONPICTURE.Text = fileName;
                        hlVISIONPICTURE.NavigateUrl = virtualPath;


                    }
                    break;
                case "btnUploadCLOSERANGEPICTURES":
                    {
                        UploadFile(this.Page, fuCLOSERANGEPICTURES, ref virtualPath, ref actualPath, ref fileName);
                        hlCLOSERANGEPICTURES.Text = fileName;
                        hlCLOSERANGEPICTURES.NavigateUrl = virtualPath;

                    }
                    break;
                case "btnUploadMACROPICTURE":
                    {
                        UploadFile(this.Page, fuMACROPICTURE, ref virtualPath, ref actualPath, ref fileName);
                        hlMACROPICTURE.Text = fileName;
                        hlMACROPICTURE.NavigateUrl = virtualPath;

                    }
                    break;

            }


        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            string _servicerepotid = String.IsNullOrEmpty(Request.QueryString["SERVICEREPOTID"]) ? "" : Request.QueryString["SERVICEREPOTID"].Trim();
            T_SERVICEQUALITYREPOT_Entity entity = bll.GetEntity("SERVICEREPOTID", _servicerepotid);

            Button btn = sender as Button;

            switch (btn.ID.ToString())
            {
                case "btnOK":
                    {
                        entity = new T_SERVICEQUALITYREPOT_Entity();
                        PageHelper.GetControlValue<T_SERVICEQUALITYREPOT_Entity>(this.Page, ref entity);
                        entity.CREATEPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                        entity.CREATEPEOPLEID = _userLoginInfo.UserEntity.USERID;
                        entity.CREATETIME = DateTime.Now;
                        entity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                        entity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
                        entity.USERTYPE = _userLoginInfo.UserEntity.USERTYPE;
                        entity.LASTMODIFYTIME = DateTime.Now;
                        entity.BUSINESSDIVISIONCODE = _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE;
                        entity.BUSINESSDIVISIONID = _userLoginInfo.UserEntity.BUSINESSDIVISIONID;
                        entity.BUSINESSDIVISIONNAME = _userLoginInfo.UserEntity.BUSINESSDIVISIONNAME;
                        entity.DEPARTMENTCODE = _userLoginInfo.UserEntity.DEPARTMENTCODE;
                        entity.DEPARTMENTID = _userLoginInfo.UserEntity.DEPARTMENTID;
                        entity.DEPARTMENTNAME = _userLoginInfo.UserEntity.DEPARTMENTNAME;
                        entity.VEHICLEPLATEIMAGE = hlVEHICLEPLATEIMAGE.Text;
                        entity.PICTURECONDITIONIMAGE = hlPICTURECONDITIONIMAGE.Text;
                        entity.VISIONPICTURE = hlVISIONPICTURE.Text;
                        entity.CLOSERANGEPICTURES = hlCLOSERANGEPICTURES.Text;
                        entity.MACROPICTURE = hlMACROPICTURE.Text;
                        entity.STATUS = ((int)ServiceQualityStatus.提交).ToString();
                        try
                        {
                            long rel = bll.Insert(entity);
                            if (rel > 0)
                            {
                                PageHelper.ShowMessage(this.Page, "提交成功！", "list.aspx");
                            }
                            else
                            {
                                PageHelper.ShowMessage(this.Page, "提交失改！");
                            }
                        }
                        catch (Exception ex)
                        {

                            PageHelper.ShowMessage(this.Page, "提交失改！" + ex.Message);
                        }

                    }
                    break;
                case "btnPass":
                    {
                        PageHelper.GetControlValue<T_SERVICEQUALITYREPOT_Entity>(this.Page, ref entity);
                        entity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                        entity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
                        entity.LASTMODIFYTIME = DateTime.Now;
                        entity.VEHICLEPLATEIMAGE = hlVEHICLEPLATEIMAGE.Text;
                        entity.PICTURECONDITIONIMAGE = hlPICTURECONDITIONIMAGE.Text;
                        entity.VISIONPICTURE = hlVISIONPICTURE.Text;
                        entity.CLOSERANGEPICTURES = hlCLOSERANGEPICTURES.Text;
                        entity.MACROPICTURE = hlMACROPICTURE.Text;
                        entity.STATUS = ((int)ServiceQualityStatus.审核通过).ToString();

                        try
                        {
                            long rel = bll.Update(entity);
                            if (rel > 0)
                            {
                                PageHelper.ShowMessage(this.Page, "审核通过成功！", UserLoginInfo.FilterBackUrl(PageHelper.GetPrePageUrl(this), "list.aspx"));
                            }
                            else
                            {
                                PageHelper.ShowMessage(this.Page, "审核通过失败！");
                            }
                        }
                        catch (Exception ex)
                        {

                            PageHelper.ShowMessage(this.Page, "审核通过失改！" + ex.Message);
                        }
                    }
                    break;
                case "btnReject":
                    {
                        PageHelper.GetControlValue<T_SERVICEQUALITYREPOT_Entity>(this.Page, ref entity);
                        entity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                        entity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
                        entity.LASTMODIFYTIME = DateTime.Now;
                        entity.VEHICLEPLATEIMAGE = hlVEHICLEPLATEIMAGE.Text;
                        entity.PICTURECONDITIONIMAGE = hlPICTURECONDITIONIMAGE.Text;
                        entity.VISIONPICTURE = hlVISIONPICTURE.Text;
                        entity.CLOSERANGEPICTURES = hlCLOSERANGEPICTURES.Text;
                        entity.MACROPICTURE = hlMACROPICTURE.Text;
                        entity.STATUS = ((int)ServiceQualityStatus.新建).ToString();


                        try
                        {
                            long rel = bll.Update(entity);
                            if (rel > 0)
                            {
                                PageHelper.ShowMessage(this.Page, "驳回成功！", UserLoginInfo.FilterBackUrl(PageHelper.GetPrePageUrl(this), "list.aspx"));
                            }
                            else
                            {
                                PageHelper.ShowMessage(this.Page, "驳回失败！");
                            }
                        }
                        catch (Exception ex)
                        {

                            PageHelper.ShowMessage(this.Page, "驳回失改！" + ex.Message);
                        }
                    }
                    break;
                case "btnReSubmit":
                    {
                        PageHelper.GetControlValue<T_SERVICEQUALITYREPOT_Entity>(this.Page, ref entity);
                        entity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                        entity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
                        entity.LASTMODIFYTIME = DateTime.Now;
                        entity.VEHICLEPLATEIMAGE = hlVEHICLEPLATEIMAGE.Text;
                        entity.PICTURECONDITIONIMAGE = hlPICTURECONDITIONIMAGE.Text;
                        entity.VISIONPICTURE = hlVISIONPICTURE.Text;
                        entity.CLOSERANGEPICTURES = hlCLOSERANGEPICTURES.Text;
                        entity.MACROPICTURE = hlMACROPICTURE.Text;
                        entity.STATUS = ((int)ServiceQualityStatus.提交).ToString();


                        try
                        {
                            long rel = bll.Update(entity);
                            if (rel > 0)
                            {
                                PageHelper.ShowMessage(this.Page, "重新提交成功！", UserLoginInfo.FilterBackUrl(PageHelper.GetPrePageUrl(this), "list.aspx"));
                            }
                            else
                            {
                                PageHelper.ShowMessage(this.Page, "重新提交失败！");
                            }
                        }
                        catch (Exception ex)
                        {

                            PageHelper.ShowMessage(this.Page, "重新提交失改！" + ex.Message);
                        }
                    }
                    break;
            }


        }


        /// <summary>
        /// 文件 上传方法
        /// </summary>
        /// <param name="page">当前页面</param>
        /// <param name="auc">上传控件</param>
        /// <returns>上传后的文件的服务器路径</returns>
        private bool UploadFile(Page page, System.Web.UI.WebControls.FileUpload auc, ref string virtualPath, ref string actualPath, ref string fileName)
        {
            bool brel = true;
            string temp = DateTime.Now.ToString("yyyyMMddHHmmss");
            string filename = auc.PostedFile.FileName;
            filename = GetFileName(filename);


            string filepath = HttpContext.Current.Request.MapPath(StaticConstant.ServiceQualityRepotImagesUploadFilePath);

            int index = filename.LastIndexOf('.');
            if (index != -1)
            {
                filename = filename.Insert(index, temp);
            }
            else
            {
                filename += temp;
            }
            fileName = filename;
            string fullpath = string.Empty;
            if (filepath.LastIndexOf("\\") == filepath.Length - 1)
            {
                fullpath = filepath + filename;
                virtualPath = StaticConstant.ServiceQualityRepotImagesUploadFilePath + filename;
            }
            else
            {
                fullpath = filepath + "\\" + filename;
                virtualPath = StaticConstant.ServiceQualityRepotImagesUploadFilePath + "\\" + filename;
            }

            try
            {
                auc.PostedFile.SaveAs(fullpath);
                actualPath = fullpath;
            }
            catch
            {
                brel = false;
                fullpath = null;
            }
            return brel;
        }

        /// <summary>
        /// Gets the virtual path.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public string GetVirtualPath(string fileName)
        {
            string virtualPath = StaticConstant.ServiceQualityRepotImagesUploadFilePath;
            if (virtualPath.LastIndexOf("\\") != virtualPath.Length - 1)
            {
                virtualPath += "\\";
            }
            virtualPath += fileName;
            return virtualPath;
        }

        /// <summary>
        /// 在绝对路径中，获取Excel文件名
        /// </summary>
        /// <param name="input">需要导入的Excel绝对路径</param>
        /// <returns></returns>
        private string GetFileName(string input)
        {
            return input.Substring(input.LastIndexOf("\\") + 1);
        }

    }
}
